package com.zhongkai.controller;

import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;
import com.zhongkai.app.service.VersionsService;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Chinaset;
import com.zhongkai.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 图片上传到图片服务器
 */
@Controller
public class PictureController {


    @Autowired
    private VersionsService versionsService;

    /**
     * 询问服务器版本号
     */

    //返回utf-8编码的数据
    @RequestMapping(value = "/pic/upload", produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public String uploaFile(@RequestParam("file") MultipartFile uploadFile) {

        try {
            //把图片上传的图片服务器


            FastDFSClient fastDFSClient = new FastDFSClient("classpath:client.conf");
            //FastDFSClient fastDFSClient = new FastDFSClient("D:\\aaa\\client.conf");
            if (uploadFile == null) {
                System.out.println("null");
            }
/*            for (MultipartFile multipartFile : uploadFile) {
                String originalFilename = multipartFile.getOriginalFilename();
                String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String url = fastDFSClient.uploadFile(multipartFile.getBytes(), extName);
                //补充为完整的url
                url = "http://111.61.64.62:8001/" + url;
            }*/

            //取文件扩展名
            String originalFilename = uploadFile.getOriginalFilename();

            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //得到一个图片的地址和文件名
            String url = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            //补充为完整的url
            url = "http://111.61.64.62:8001/" + url;
            //封装到map中返回
            Map result = new HashMap();
            result.put("error", 0);
            result.put("url", url);
            return new Gson().toJson(result);
        } catch (Exception e) {
            e.printStackTrace();
            Map result = new HashMap();
            result.put("error", 1);
            result.put("message", "图片上传失败");
            return new Gson().toJson(result);
        }
    }


    /**
     * 上传系统版本
     * , produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8", method = RequestMethod.POST
     *
     * @param file 文件
     * @param ver 版本号
     */

    @RequestMapping(value = "/pic/versions",produces = "application/json;charset=utf-8")
    @ResponseBody
   // @CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    public ZhongkaiResult uploaFileVer(@RequestParam("file") CommonsMultipartFile file, String ver, HttpServletRequest httpServletRequest, HttpServletResponse response) {


        //response.setHeader("Access-Control-Allow-Methods", "*");
/*
        if (httpServletRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
            System.out.println("200执行");
            response.setStatus(200);
            return ZhongkaiResult.ok();
        }
*/

        if (StringUtils.isNullOrEmpty(ver)) {
            return ZhongkaiResult.build(500, "参数不完整");
        }

        //System.out.println(ver);
        String prc = "^\\d+\\.\\d+\\.\\d+$";

        ver = ver.trim(); //去除空格

        if (!Pattern.matches(prc, ver.trim())) { //正则验证1.0.1的格式

            return ZhongkaiResult.build(500, "版本号格式不合法1");
        }

        ZhongkaiResult upload = versionsService.upload(ver); //验证版本号

        if (upload.getStatus() == 500){
            return upload;
        }


        try {


            FastDFSClient fastDFSClient = new FastDFSClient("classpath:client.conf"); //把图片上传的图片服务器
            //FastDFSClient fastDFSClient = new FastDFSClient("D:\\aaa\\client.conf");

            if (file.isEmpty()) {
                return ZhongkaiResult.build(500, "上传文件不能为空");
            }
/*            for (MultipartFile multipartFile : uploadFile) {
                String originalFilename = multipartFile.getOriginalFilename();
                String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String url = fastDFSClient.uploadFile(multipartFile.getBytes(), extName);
                //补充为完整的url
                url = "http://111.61.64.62:8001/" + url;
            }*/


            String originalFilename = file.getOriginalFilename();//取文件名以及扩展名

            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); //文件扩展名

            String url = fastDFSClient.uploadFile(file.getBytes(), extName);//得到一个图片的地址和文件名

            url = "http://111.61.64.62:8001/" + url;//补充为完整的url-

            //uploadFile.getOriginalFilename()
//===================================================本地存储==================================================================

            String separator = File.separator; //获取系统文件符号 可跨平台

            String[] split = httpServletRequest.getSession().getServletContext().getRealPath(separator).split("webapps");
            String filePath =  split[0]+ "upload"+ separator;//获取项目本地地址

/*            System.out.println(separator+"啊啊啊啊啊啊啊");
            System.out.println(filePath);*/

            File file2 = new File(filePath); //创建文件夹
            file2.setWritable(true,false);
            if (!file2.exists()) {  //检测文件夹是否存在  不存在则创建
                file2.mkdir();
            }


            String upload_dist = filePath + originalFilename;


           // System.out.println(upload_dist);
           // System.out.println(filePath + extName);
            File descFile = new File(upload_dist); //得到目标file

            //若文件存在重命名
            int i = 1;
            while(descFile.exists()) {

                originalFilename = originalFilename.replace("."+extName,"")+"("+i+")."+extName; //完整文件名
                upload_dist  =  filePath+originalFilename; //得到新的文件路径
                descFile = new File(upload_dist);
/*
                System.out.println(originalFilename);
                System.out.println(filePath);*/
                i++;
            }


            file.transferTo(descFile); //存入本地一份

            String war_uuid = TTHelp.generate();
            Chinaset chinaset = (Chinaset) httpServletRequest.getAttribute("user");





            ZhongkaiResult result = versionsService.uploadSystem(ver, url, upload_dist,chinaset.getSetName(),chinaset.getUuid());

          //  ZhongkaiResult result = versionsService.uploadSystem(ver, url, filePath+originalFilename,"111","111");
            return result;
        } catch (Exception e) {
            e.printStackTrace();

            return ZhongkaiResult.build(500, "上传失败");
        }
    }





    /**
     * 系统列表
     *
     * @param page      页数
     * @param rows      条数
     * @param is_default 1默认 2非默认
     */
    @RequestMapping(value = "/pic/list", produces = "application/json;charset=utf-8")
    @ResponseBody
    public ZhongkaiResult uploadSystemList( @RequestParam(defaultValue = "0")Integer page,@RequestParam(defaultValue = "0")Integer rows,@RequestParam(defaultValue = "0")Integer is_default) {

       // Chinaset chinaset = (Chinaset) httpServletRequest.getAttribute("user");
        ZhongkaiResult result = versionsService.uploadSystemList(page,rows,is_default);

        return result;
    }



    /**
     * 设为默认
     * @param id      系统id
     */
    @RequestMapping(value = "/pic/set_default", produces = "application/json;charset=utf-8")
    @ResponseBody
    public ZhongkaiResult setDefault( @RequestParam(defaultValue = "0")Long id) {

        // Chinaset chinaset = (Chinaset) httpServletRequest.getAttribute("user");
        ZhongkaiResult result = versionsService.setDefault(id);

        return result;
    }



    /**
     * 删除
     * @param id      系统id
     */
    @RequestMapping(value = "/pic/remove", produces = "application/json;charset=utf-8")
    @ResponseBody
    public ZhongkaiResult removeVer( @RequestParam(defaultValue = "0")Long id) {

        // Chinaset chinaset = (Chinaset) httpServletRequest.getAttribute("user");
        ZhongkaiResult result = versionsService.removeVer(id);

        return result;
    }


    /**
     * 取消默认
     * @param id      系统id
     */
    @RequestMapping(value = "/pic/cancel_default", produces = "application/json;charset=utf-8")
    @ResponseBody
    public ZhongkaiResult cancelDefault( @RequestParam(defaultValue = "0")Long id) {

        // Chinaset chinaset = (Chinaset) httpServletRequest.getAttribute("user");
        ZhongkaiResult result = versionsService.cancelDefault(id);

        return result;
    }
}
